<template>
    <Modal
        :value="value"
        input="modalChange"
        width="60%"
        :mask-closable="false"
        @on-cancel="onCancel"
        @on-visible-change="handleVisibleChange"
    >
        <Form :label-width="88" inline @submit.native.prevent>
            <FormItem label="商品编码">
                <Input
                    class="medium-input"
                    type="text"
                    placeholder="请输入商品名称"
                    ref="input"
                    @on-enter="search"
                    @on-focus="isFocus = true"
                    @on-blur="isFocus = false"
                    v-model="goodsCoding"
                ></Input>
            </FormItem>
            <FormItem>
                <Button class="icon-btn" type="primary" @click="search">查询</Button>
            </FormItem>
        </Form>
        <Table :height="383" :loading="loading" :columns="goodsColumns" :data="goodsList"></Table>
        <Pagination
            class="goods-page"
            :pageSize.sync="pageSize"
            :current.sync="pageNum"
            :total="total"
            @change="queryGoods"
        />
        <div slot="footer">
            <Button type="default" @click="onCancel">取消</Button>
            <Button type="primary" @click="onOk">确定</Button>
        </div>
    </Modal>
</template>
<script>
import { on, off } from '@/libs/tools'
import { getPro } from '@/api/commodityManage'
export default {
    props: {
        value: {
            type: Boolean,
            default: false
        },
        coding: {
            type: String,
            default: ''
        }
    },
    data () {
        return {
            loading: false,
            goodsCoding: '',
            pageNum: 1,
            total: 0,
            pageSize: 10,
            goodsList: [],
            goodsColumns: [
                {
                    title: '单选',
                    key: 'check',
                    width: 80,
                    align: 'center',
                    render: (h, params) => {
                        const self = this
                        return h('Checkbox', {
                            props: {
                                value: params.row.check
                            },
                            on: {
                                input: function () {
                                    const checked = self.goodsList.findIndex(
                                        item => item.check
                                    )
                                    if (checked >= 0 && params.index !== checked) self.goodsList[checked].check = false
                                    self.goodsList[params.index].check = !self.goodsList[params.index].check
                                }
                            }
                        })
                    }
                },
                {
                    title: '商品编号',
                    key: 'codeTs',
                    align: 'center',
                    width: 120
                },
                {
                    title: '商品名称',
                    key: 'goodsName',
                    tooltip: true,
                    align: 'center',
                    minWidth: 240
                }
            ],
            isFocus: false
        }
    },
    methods: {
        search () {
            if (this.goodsCoding && this.goodsCoding.length >= 4) {
                this.pageNum = 1
                this.queryGoods()
            } else {
                this.$Message.warning('请至少输入四位商品编码')
            }
        },
        queryGoods () {
            this.loading = true
            getPro({
                keyWord: this.goodsCoding,
                pageNum: this.pageNum,
                pageSize: this.pageSize
            }).then(res => {
                if (res.data.code === '0000') {
                    const list = res.data.data.list
                    this.goodsList = list.map((item, index) => {
                        return {
                            codeTs: item.codeTs,
                            goodsName: item.goodsName,
                            firstUnit: item.firstUnit,
                            firstUnitCNH: item.firstUnitCNH,
                            secondUnit: item.secondUnit,
                            secondUnitCNH: item.secondUnitCNH,
                            check: index === 0
                        }
                    })
                    this.total = res.data.data.total
                    if (list.length) {
                        this.$refs.input.blur()
                    } else {
                        this.$refs.input.focus()
                    }
                }
                this.loading = false
            }).catch(err => {
                this.loading = false
                console.log(err)
            })
        },
        modalChange (v) {
            this.$emit('input', v)
        },
        onOk () {
            const checked = this.goodsList.find(item => item.check)
            if (checked) {
                this.modalChange(false)
                this.$emit('on-ok', checked)
            } else {
                this.$Message.warning('请选择商品')
            }
        },
        onCancel () {
            this.$emit('input', false)
            this.$emit('on-cancel')
        },
        getCheckIndex () {
            return this.goodsList.findIndex(item => item.check)
        },
        handleKeyboardEvent (event) {
            if (!this.value || this.isFocus) return
            const keyCode = event.keyCode
            if (event.type === 'keyup') {
                if (keyCode === 13) {
                    this.onOk()
                }
            } else {
                switch (keyCode) {
                    // 上键 38
                    case 38:
                        event.preventDefault()
                        let index = this.getCheckIndex()
                        if (index > 0) {
                            this.goodsList[index].check = false
                            this.goodsList[index - 1].check = true
                        }
                        break
                    // 下键 40
                    case 40:
                        event.preventDefault()
                        const j = this.getCheckIndex()
                        if (j < this.goodsList.length - 1) {
                            this.goodsList[j].check = false
                            this.goodsList[j + 1].check = true
                        }
                        break
                }
            }
        },
        // 处理弹窗状态改变
        handleVisibleChange (v) {
            const fn = v ? on : off
            // 绑定 键盘 事件
            fn(window, 'keydown', this.handleKeyboardEvent)
            fn(window, 'keyup', this.handleKeyboardEvent)
            // 搜索商品
            if (!v) return
            if (this.goodsCoding !== this.coding) {
                this.goodsCoding = this.coding
                this.search()
            } else {
                this.goodsList = this.goodsList.slice()
            }
        }
    }
}
</script>
<style lang="less" scoped>
.goods-page {
    text-align: right;
    margin-top: 15px;
}
</style>
